package com.woorigil.social.parser;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import nu.xom.Element;
import nu.xom.ParsingException;
import nu.xom.ValidityException;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.woorigil.social.domain.ProviderCode;
import com.woorigil.social.domain.category.CategoryMapper;
import com.woorigil.social.domain.category.CategoryMapperFactory;
import com.woorigil.social.domain.deal.Deal;
import com.woorigil.social.domain.deal.DealListDocument;

public abstract class XmlParser {
	@Autowired CategoryMapperFactory categoryMapperFactory;
	
	abstract public String getCharsetName();
	abstract public ProviderCode getProviderCode();
	abstract public String getSourcePath();
	abstract public DealListDocument parse(Reader reader) throws ValidityException, ParsingException, IOException;

	public DealListDocument parse(String xml) {
		DealListDocument dealList = new DealListDocument();
		return dealList;
	}
	
	public DealListDocument parse(InputStream is) throws ValidityException, ParsingException, IOException {
		return parse(new InputStreamReader(is, "UTF-8"));
	}
	
	protected int computeDiscountRate(double originalPrice, double salesPrice) {
		double rate = ((originalPrice - salesPrice) / originalPrice) * 100;
		return (int) rate;
	}

	protected String getValue(Element element) {
		if (element == null) {
			return null;
		}
		return StringUtils.trim(element.getValue());
	}
	
	protected int findCategoryId(ProviderCode providerCode, Deal deal) {
		try {
			CategoryMapper mapper = categoryMapperFactory.getInstance(providerCode);
			return mapper.getCategoryId(deal);
		} catch (Exception e) {
//			e.printStackTrace();
			return 0;
		}
	}
}
